package org.ifilm.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.ifilm.model.Project;
import org.springframework.stereotype.Repository;

@Repository
public class ProjectDaoImpl implements ProjectDao {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public Project createProject(Project project) {
		return entityManager.merge(project);
	}
	
	@Override
	public Project getProject(Long id) {
		try {
			Query query = entityManager.createQuery(getProjectQuery());
			query.setParameter("id", id);
			return (Project) query.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public String getProjectQuery() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("select p from project p where p.id=:id");
		return strBuild.toString();
	}
	
	@Override
	public List<Project> listProjects(Integer page, Integer max) {
		try {
			Query query = entityManager.createQuery(listAllProjectsQuery());
			query.setFirstResult((page - 1) * max);
			query.setMaxResults(max);
			return (List<Project>) query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String listAllProjectsQuery() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("select p from project p order by p.id DESC");
		return strBuild.toString();
	}
}